from flask import Blueprint, flash, render_template, redirect, url_for, request, abort
from flask_login import login_required, current_user

from blog import db
from .forms import PostForm
from .models import Post


post = Blueprint('post', __name__)


@post.route('/post/new', methods=['GET', 'POST'])
@login_required
def create_post():
    form = PostForm()
    if form.validate_on_submit():
        new_post = Post(
            title=form.title.data,
            content=form.content.data,
            user=current_user
        )
        db.session.add(new_post)
        db.session.commit()
        flash('文章创建成功', category='success')
        return redirect(url_for('main.index'))
    return render_template('create_post.html', title='写文章', form=form)


@post.route('/post/<int:post_id>')
def post_detail(post_id):
    # 如果不存在返回404页面
    post = Post.query.get_or_404(post_id)
    return render_template('post_detail.html', title=post.title, post=post)


@post.route('/post/<int:post_id>/edit', methods=['GET', 'POST'])
@login_required
def update_post(post_id):
    post = Post.query.get_or_404(post_id)
    # 只能更改自己的文章
    if post.user != current_user:
        abort(403)  # Forbidden
    form = PostForm()
    # 自动填充原来的数据
    if request.method == 'GET':
        form.title.data = post.title
        form.content.data = post.content

    if form.validate_on_submit():
        post.title = form.title.data
        post.content = form.content.data
        # 不需要db.session.commit()因为数据库里面已经存在
        db.session.commit()
        flash('文章更改成功！', category='success')
        return redirect(url_for('post.post_detail', post_id=post.id))

    return render_template('update_post.html', title='更改文章', form=form)


@post.route('/post/<int:post_id>/delete', methods=['POST'])  # 405 Method Not Allowed
@login_required
def delete_post(post_id):
    post = Post.query.get_or_404(post_id)
    # 只能删除自己的文章
    if post.user != current_user:
        abort(403)  # Forbidden
    db.session.delete(post)
    db.session.commit()
    flash('文章删除成功！', category='success')
    return redirect(url_for('main.index'))

